package ltesim.wizards.channel;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import java.io.*;

import org.eclipse.ui.*;

/**
 *
 */

public class LteSimNewChannel extends Wizard implements INewWizard {
	private LteSimNewChannelPage page;
	private ISelection selection;

	/**
	 * Constructor for LteSimNewChannel.
	 */
	public LteSimNewChannel() {
		super();
		setNeedsProgressMonitor(true);
	}

	/**
	 * Adding the page to the wizard.
	 */

	@Override
	public void addPages() {
		page = new LteSimNewChannelPage(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in the wizard. We
	 * will create an operation and run it using wizard as execution context.
	 */
	@Override
	public boolean performFinish() {
		final String containerName = page.getContainerName();
		final String fileName = page.getFileName();
		IRunnableWithProgress op = new IRunnableWithProgress() {
			@Override
			public void run(IProgressMonitor monitor)
					throws InvocationTargetException {
				try {
					doFinish(containerName, fileName, monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error",
					realException.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * The worker method. It will find the container, create the file if missing
	 * or just replace its contents, and open the editor on the newly created
	 * file.
	 */

	private void doFinish(String projectRoot, String channelName,
			IProgressMonitor monitor) throws CoreException {

		monitor.beginTask("Creating Channel_" + channelName, 2);
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = root.findMember(new Path(projectRoot));
		if (!resource.exists() || !(resource instanceof IContainer)) {
			throwCoreException(projectRoot + "\" does not exist.");
		}
		IContainer container = (IContainer) resource;

		CreateDirectory(container, channelName, monitor);

		CreateDefaultFiles(container, channelName, monitor);

		monitor.worked(1);
		/*
		 * monitor.setTaskName("Opening file for editing...");
		 * getShell().getDisplay().asyncExec(new Runnable() { public void run()
		 * { IWorkbenchPage page =
		 * PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		 * try { IDE.openEditor(page, file, true); } catch (PartInitException e)
		 * { } } }); monitor.worked(1);
		 */
	}

	private void CreateDefaultFiles(IContainer container, String channelName,
			IProgressMonitor monitor) {

		String defaultFName = "channel" + channelName + ".cpp";
		String defaultFDir = "Channel/Channel" + channelName + "/src/";
		final IFile file = container.getFile(new Path(defaultFDir
				+ defaultFName));
		try {
			InputStream stream = getDefaultFileContent(channelName);
			if (file.exists()) {
				try {
					file.setContents(stream, true, true, monitor);
				} catch (CoreException e) {
					e.printStackTrace();
				}
			} else {
				try {
					file.create(stream, true, monitor);
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}
			stream.close();
		} catch (IOException e) {
		}

	}

	private void CreateDirectory(IContainer container, String channelName,
			IProgressMonitor monitor) {
		String[] paths = { "Channel/", "Channel/Channel_" + channelName + "/",
				"Channel/Channel_" + channelName + "/src" };

		for (String dir : paths) {
			IFolder fold = container.getFolder(new Path(dir));
			if (!fold.exists()) {
				try {
					fold.create(true, true, monitor);
				} catch (CoreException e) {
					e.printStackTrace();
				}
				System.out.println("Creating directory: " + dir);
			}
		}
	}

	/**
	 * We will initialize file contents with a sample text.
	 */

	private InputStream getDefaultFileContent(String channelName) {
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss");
		String dateNow = formatter.format(currentDate.getTime());
		String DefaultFileContent = "/*****************************************************************************\n"
				+ "** \n"
				+ "**  File : Channel_"
				+ channelName
				+ "\n"
				+ "**  Date : "
				+ dateNow
				+ "\n"
				+ "** \n"
				+ "*****************************************************************************/\n";

		return new ByteArrayInputStream(DefaultFileContent.getBytes());
	}

	private void throwCoreException(String message) throws CoreException {
		IStatus status = new Status(IStatus.ERROR, "ltesim", IStatus.OK,
				message, null);
		throw new CoreException(status);
	}

	/**
	 * We will accept the selection in the workbench to see if we can initialize
	 * from it.
	 * 
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
}